package com.lixin.rabbitmq.routing;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeoutException;

/**
 * '*'号代表有且只能有一级
 *  '#'号代表可以没有，也可以有任意级
 */
public class Producer {
    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.3.17");
        factory.setPort(5672);
        factory.setUsername("admin");
        factory.setPassword("123456");
        factory.setVirtualHost("/");
        try {
            // 创建连接connection
            connection = factory.newConnection("adminConn");
            // 创建通道channel
            channel = connection.createChannel();
            // 消息内容
            //String message = "发布/订阅模式消息";
            //String message = "发布/订阅模式，带路由KEY的消息";
            String message = "发布/订阅模式，路由KEY模糊匹配的消息";
            // 交换机名称
            //String exchangeName = "fanoutExchange";
            //String exchangeName = "directExchange";
            String exchangeName = "topicExchange";
            // 路由key
            //String routingKey = "";
            //String routingKey = "email";
            String routingKey = "order.payment.user";
            // 交换机类型
            //String exchangeType = "fanout";
            //String exchangeType = "direct";
            String exchangeType = "topic";
            // 发送消息给交换机(交换机会将消息投递到所有和其绑定的队列中)
            channel.basicPublish(exchangeName, routingKey, null, message.getBytes(StandardCharsets.UTF_8));
            System.out.println("消息成功发送！");
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        } finally {
            // 关闭通道
            if (channel != null && channel.isOpen()) {
                try {
                    channel.close();
                } catch (IOException | TimeoutException e) {
                    e.printStackTrace();
                }
            }
            // 关闭连接
            if (connection != null && connection.isOpen()) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
